﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

using MxitAPI;

namespace MxitGUI {
    
    public partial class MainWindow : Form {

        private ChatWindowContainer chatWindowContainer;

        private ChatSessions chatSessions;
        private Contacts contacts;
        private LoginWindow loginWindow;
        //private ContactsList contactList;

        public MainWindow( LoginWindow loginWindow ) {
            InitializeComponent();
            this.loginWindow = loginWindow;
            Init();
        }

        public void Init() {

            ApplicationInfo.Instance.ProtocolMessageError += HandleProtocolMessageError;

            chatSessions = ChatSessions.Instance;
            contacts = Contacts.Instance;

            // Initialise the contactsList control
            contactList.Init( contacts, chatSessions );
            contactList.UpdateContacts();

            // Create the tabbed chat window
            chatWindowContainer = new ChatWindowContainer( chatSessions, contacts );
            chatWindowContainer.Show();

            // Get this users profile
            GetProfileHandler getProfileHandler = new GetProfileHandler();
            getProfileHandler.Execute();

            // Initialize the mood combobox
            int cmbMoodSelectIndex = cmbMood.Items.Add( Mood.None );
            cmbMood.Items.Add( Mood.Angry );
            cmbMood.Items.Add( Mood.Excited );
            cmbMood.Items.Add( Mood.Grumpy );
            cmbMood.Items.Add( Mood.Happy );
            cmbMood.Items.Add( Mood.Hot );
            cmbMood.Items.Add( Mood.InLove );
            cmbMood.Items.Add( Mood.Invincible );
            cmbMood.Items.Add( Mood.Sad );
            cmbMood.Items.Add( Mood.Sick );
            cmbMood.Items.Add( Mood.Sleepy );
            cmbMood.SelectedIndex = cmbMoodSelectIndex;

            // Initialize the status combobox
            int cmbPresenceSelectedIndex = cmbPresence.Items.Add( Presence.Online );
            cmbPresence.Items.Add( Presence.DoNotDisturb );
            cmbPresence.Items.Add( Presence.Away );
            cmbPresence.SelectedIndex = cmbPresenceSelectedIndex;            
            

            // Look for new contact subscription requests
            GetNewSubscriptionHandler getNewSubscriptionHandler = new GetNewSubscriptionHandler();
            getNewSubscriptionHandler.Execute();

            // Add events to listen for
            ChatSessions.Instance.NewMessagesReceived += new ChatSessionsEventHandler( HandleNewMessagesReceived );

            // Get any new messages
            ( new GetNewMessagesHandler() ).Execute();


        }

        private void loginToolStripMenuItem_Click( object sender, EventArgs e ) {

        }

        private void HandleNewMessagesReceived( ChatSessions chatSessions, AffectedChatSessionsEventArgs e ) {
            if ( InvokeRequired ) {
                Invoke( new ChatSessionsEventHandler( HandleNewMessagesReceived ), chatSessions, e );
            }

            // Update the contacts list to show that a new message has been received
            foreach ( ChatSession chatSession in e.AffectedChatSession ) {
                //
                //chatSession.ContactId;
            }

            //chatWindowContainer.TryAddNewChatSessions( chatSessions )

            /*while ( chatSessions.NewMessagesExist() ) {
                ChatSession c = chatSessions.GetNextChatSessionWithNewMessages();
                chatWindowContainer.
            }*/

        }

        private void btnAddContact_Click( object sender, EventArgs e ) {
            ( new AddContactWindow() ).ShowDialog();
        }

        private void HandleProtocolMessageError( Handler sender, ProtocolMessageErrorEventArgs e ) {
            try {
                MessageBox.Show( "Error code: " + e.ProtocolMessage.ErrorCode + Environment.NewLine +
                    "Error message: " + e.ProtocolMessage.ErrorMessage, "MXit Error" );
            }
            catch ( Exception ex ) {
                MessageBox.Show( "An error occured while communicating with MXit" );
            }
        }

        private void cmbMood_SelectedIndexChanged( object sender, EventArgs e ) {
            SetMoodHandler handler = new SetMoodHandler( ( Mood ) cmbMood.SelectedItem );
            handler.Execute();
        }

        private void HandleSetPresence( object sender, EventArgs e ) {
            SetPresenceHandler handler = new SetPresenceHandler( ( Presence ) cmbPresence.SelectedItem, txtStatus.Text );
            handler.Execute();
        }

        private void txtStatus_KeyDown( object sender, KeyEventArgs e ) {
            if ( e.KeyCode == Keys.Enter )
                HandleSetPresence( sender, e );
        }

        private void btnAddGateway_Click( object sender, EventArgs e ) {
            AddGatewayWindow addGatewayWindow = new AddGatewayWindow();
            addGatewayWindow.ShowDialog();
        }

        private void btnRemoveGateway_Click( object sender, EventArgs e ) {
            RemoveGatewayWindow removeGatewayWindow = new RemoveGatewayWindow();
            removeGatewayWindow.ShowDialog();
        }

        private void btnLogout_Click( object sender, EventArgs e ) {
            ( new LogoutHandler() ).Execute();
            Environment.Exit( 0 );
            /*chatWindowContainer.Quit();
            loginWindow.Exit();
            loginWindow.Dispose();
            chatWindowContainer.Dispose();
            //Dispose();
            Application.Exit();*/
            //new LoginWindow().Show();
            /*System.Threading.Thread.Sleep( 3000 );
            chatWindowContainer.Close();
            Close();
            
            Application.Exit();*/
            
        }

        private void btnProfile_Click( object sender, EventArgs e ) {
            new UserProfileWindow().ShowDialog();
        }

        private void MainWindow_FormClosing( object sender, FormClosingEventArgs e ) {
            Environment.Exit( 0 );
        }


    }
}
